<template>
  <div class="main content" @click="handleCloseMenu">
    <el-container class="container-box">
      <!--  侧边栏    -->
      <el-aside class="dataSourceList" width="200px;" style="padding-bottom: 10px">
        <div class="module-title">
          <span class="title">数据源中心</span>
          <!-- <el-icon><Plus @click="addTab" class="addBtn" /></el-icon> -->
          <div @click="addTab" class="addBtn">新增</div>
        </div>
        <!--   搜索数据库     -->
        <!-- <el-input v-model="searchDatasource" :prefix-icon="Search" class="search"></el-input> -->
        <!--   根据数据库类型搜索     -->
        <div class="businessType">
          <!-- <el-select
          v-model="selectType"
          @change="selectChange"
          class="type"
          clearable
          filterable
          placeholder="请选择业务类型"
        >
          <el-option
            v-for="dbType in dataBaseType"
            :key="dbType.dictValue"
            :label="dbType.dictLabel"
            :value="dbType.dictValue"
          ></el-option>
        </el-select> -->
          <el-select
            v-model="selectDatasourceType"
            @change="selectChange"
            class="type"
            clearable
            filterable
            placeholder="请选择数据库类型"
          >
            <el-option
              v-for="dbType in dbTypeList"
              :key="dbType.dictLabel"
              :label="dbType.dictLabel"
              :value="dbType.dictLabel"
            ></el-option>
          </el-select>
        </div>
        <el-input
          class="databaseNameInput"
          v-model="selectName"
          @input="selectChange"
          placeholder="请输入数据库名称"
        ></el-input>

        <!--   数据库列表     -->
        <!-- <ul class="list" v-loading="listLoading">
          <li
            v-for="datasource in datasourceListFilter"
            :key="datasource"
            @click="
              () => {
                handleOpenDialog(datasource)
              }
            "
            @contextmenu.prevent.native="openMenu($event, datasource)"
          >
            {{ datasource.datasourceName }}
          </li>
        </ul> -->
        <el-tree
          :data="datasourceTree"
          :props="defaultProps"
          @node-contextmenu="nodeContextmenu"
          @node-click="handleNodeClick"
          v-loading="treeLoading"
        >
          <template #default="{ data }">
            <span class="custom-tree-node" style="display: flex; align-items: center">
              <span v-if="data.type == 'MongoDB'">
                <img src="../../assets/image/database/MongoDB.png" alt="" />
              </span>
              <span v-else-if="data.type == 'Oracle'">
                <img src="../../assets/image/database/oracle.png" alt="" />
              </span>
              <span v-else-if="data.type == 'ElasticSearch'">
                <img src="../../assets/image/database/elasticsearch.png" alt="" />
              </span>
              <span v-else-if="data.type == 'MySQL'">
                <img src="../../assets/image/database/mysql.png" alt="" />
              </span>
              <span v-else-if="data.type == 'Kafka'">
                <img src="../../assets/image/database/Kafka.png" alt="" />
              </span>
              <span v-else-if="data.type == 'ClickHouse'">
                <img src="../../assets/image/database/clickhouse.png" alt="" />
              </span>
              <span v-else-if="data.type == 'SQLServer'">
                <img src="../../assets/image/database/sqlserver.png" alt="" />
              </span>
              <span style="padding-left: 10px">
                {{ data.datasourceName }}
              </span>
            </span>
          </template>
        </el-tree>
      </el-aside>
      <!--   main   -->
      <el-main class="dataSourceMain" style="position: relative; z-index: 999; width: calc(100% - 300px)">
        <div :class="`container-box-main ${editableTabs.length > 0 ? '' : 'act'}`">
          <el-tabs
            v-if="editableTabs.length > 0"
            v-model="editableTabsValue"
            type="card"
            class="demo-tabs animate animate__animated animate__fadeIn"
            closable
            @tab-remove="removeTab"
            @tab-click="tabClick"
          >
            <el-tab-pane v-for="item in editableTabs" :key="item.name" :label="item.title" :name="item.name">
              <!--      新增        -->
              <AddDatasource
                class="animate__animated animate__fadeIn"
                v-if="item.title === '新增数据源'"
                @refresh="handleRefresh"
                style="height: 100%"
              />
              <ModifyDatasource
                class="animate__animated animate__fadeIn"
                v-else-if="item.title.slice(0, 5) === '修改数据源'"
                :datasource="modifyDatasource"
                :modifyKey="modifyKey"
                @refresh="handleRefresh"
                style="height: 100%"
              />
              <DatasourceUser
                class="animate__animated animate__fadeIn"
                v-else-if="item.title.slice(0, 4) === '用户管理'"
                :datasource="modifyDatasource"
                :modifyKey="modifyKey"
              />
              <!--      查/改        -->
              <DatabaseInfo
                v-else
                ref="DatabaseInfoRef"
                class="animate__animated animate__fadeIn"
                :data="data"
                :list="datasourceList"
                :esList="esList"
                :ckList="ckList"
                :pgList="pgList"
                :mysqlList="mysqlList"
                style="height: 100%"
              />
            </el-tab-pane>
          </el-tabs>

          <!-- <div v-else>
            <div class="moduleContainer">
              <div class="businessCard">
                <div class="titleContent">
                  <img src="@/assets/image/blueTitleIcon.png" alt="" class="titleIcon" />
                  <span class="title">业务类型连接数</span>
                </div>

                <div class="dataCardList">
                  <div class="dataCard" v-for="(item, index) in businessCardList" :key="index">
                    <div class="dataCardTitle">{{ item.type }}</div>
                    <div class="dataCardNum">{{ item.value }}</div>
                  </div>
                </div>
              </div>

              <div class="businessTrend">
                <div class="titleContent">
                  <img src="@/assets/image/blueTitleIcon.png" alt="" class="titleIcon" />
                  <span class="title">业务类型连接数增长趋势</span>
                </div>

                <LineChart :data="businessTrendData" />
              </div>
            </div>

            <div class="moduleContainer noFlex">
              <div class="databaseTypeCard">
                <div class="titleContent">
                  <img src="@/assets/image/blueTitleIcon.png" alt="" class="titleIcon" />
                  <span class="title">数据库类型连接数</span>
                </div>

                <div class="databaseTypeCardList">
                  <div class="databaseTypeCard" v-for="(item, index) in databaseTypeCard" :key="index">
                    <div class="databaseIcon">
                      <img v-if="item.type" :src="findSqlType(item.type)" alt="" />
                    </div>
                    <div class="rightContent">
                      <div class="dataCardNum">{{ item.value }}</div>
                      <div class="dataCardTitle">{{ item.type }}</div>
                    </div>
                  </div>
                </div>
              </div>

              <div class="databaseTypeChart">
                <div class="databaseTypeChartCard">
                  <div class="titleContent">
                    <img src="@/assets/image/blueTitleIcon.png" alt="" class="titleIcon" />
                    <span class="title">数据库类型连接数</span>
                  </div>

                  <BarChart :data="barData" />
                </div>

                <div class="databaseTypeBarChartCard">
                  <div class="titleContent">
                    <img src="@/assets/image/blueTitleIcon.png" alt="" class="titleIcon" />
                    <span class="title">数据库类型分布情况</span>
                  </div>

                  <PieChart :data="pieData" />
                </div>
              </div>
            </div>
          </div> -->
        </div>
      </el-main>
    </el-container>
    <ul v-show="showMenu" :style="{ left: left + 'px', top: top + 'px' }" class="contextmenu">
      <li @click="handleClickDatasource">修改</li>
      <!-- <li @click="handleClickUser">用户管理</li> -->
      <!-- <li @click="handleClickStarrockts">创建starrockts配置</li> -->
      <!-- <li @click="handleClickDoris">创建doris配置</li> -->
      <!-- <li @click="handleClickCreateTable">创建表结构</li> -->
    </ul>
    <StarrocktsConfig v-model:visible="isShowStarrocktsDialog" :datasource="currentDatasource" />
    <DorisConfig v-model:visible="isShowDorisDialog" :dorisList="dorisList" :datasource="currentDatasource" />
    <CreateTableConfig
      v-model:visible="isShowCreateTableDialog"
      :datasourceList="datasourceList"
      :dbTypeList="dbTypeList"
      :datasource="currentDatasource"
    />
  </div>
</template>

<script setup>
import AddDatasource from './components/addDatasource.vue'
import ModifyDatasource from './components/modifyDatasource.vue'
import DatabaseInfo from './components/databaseInfo.vue'
import DatasourceUser from './components/datasourceUser.vue'
import { Plus, Search } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import {
  getDatabaseList,
  getDatabaseTree,
  createDBTypeList,
  findCountByBusiness,
  findTrendByBusiness,
  findCountByType
} from '@/api/datasourceCenter'
import _cloneDeep from 'lodash/cloneDeep'
// import { getDictType } from '@/api/system/dictionary'
import { ref } from 'vue-demi'
import StarrocktsConfig from './components/starrocktsConfig.vue'
import DorisConfig from './components/dorisConfig.vue'
import CreateTableConfig from './components/createTableConfig.vue'

import LineChart from './components/LineChart.vue'
import BarChart from './components/BarChart.vue'
import PieChart from './components/PieChart.vue'

import gbase from '@/assets/database/GBase.jpeg'
import greatdb from '@/assets/database/GreatDB.png'
import highgo from '@/assets/database/Highgo.jpeg'
import kingbasees from '@/assets/database/KingbaseES.jpeg'
import polardb from '@/assets/database/PolarDB.png'
import seaboxsql from '@/assets/database/SeaboxSQL.jpeg'
import tdsql from '@/assets/database/TdSQL.png'
import uxdb from '@/assets/database/UxDB.jpeg'
import vastbase from '@/assets/database/VastBase.png'
import xugudb from '@/assets/database/XuguDB.png'
import duckdb from '@/assets/image/DuckDB.png'
import mysql from '@/assets/image/MySQL.png'
import oracle from '@/assets/image/Oracle.png'
import elasticsearch from '@/assets/image/ElasticSearch.png'
import mongodb from '@/assets/database/MongoDB.png'
import kafka from '@/assets/database/Kafka.png'
import clickhouse from '@/assets/image/ClickHouse.png'
import sqlserver from '@/assets/image/SQLServer.png'
import dameng from '@/assets/image/DaMeng.png'
import postgresql from '@/assets/image/PostgreSQL.png'
import starrocks from '@/assets/image/starrocks.png'
import doris from '@/assets/image/doris.png'

const DatabaseInfoRef = ref()
const datasourceList = ref([]) // 数据库列表
const datasourceTree = ref([]) // 数据库列表
const dataBaseType = ref([])
const treeLoading = ref(false)
const isShowStarrocktsDialog = ref(false)
const isShowDorisDialog = ref(false)
const defaultProps = {
  children: 'children',
  label: 'datasourceName'
}
// getDictType('dataBaseType').then((res) => {
//   dataBaseType.value = res.data
// })

const findSqlType = (type) => {
  if (!type) {
    return
  }
  //转换为小写
  let lowerType = type.toLowerCase()
  switch (lowerType) {
    case 'gbase':
      return gbase
    case 'greatdb':
      return greatdb
    case 'highgo':
      return highgo
    case 'kingbasees':
      return kingbasees
    case 'polardb':
      return polardb
    case 'seaboxsql':
      return seaboxsql
    case 'tdsql':
      return tdsql
    case 'uxdb':
      return uxdb
    case 'vastbase':
      return vastbase
    case 'xugudb':
      return xugudb
    case 'duckdb':
      return duckdb
    case 'mysql':
      return mysql
    case 'oracle':
      return oracle
    case 'elasticsearch':
      return elasticsearch
    case 'mongodb':
      return mongodb
    case 'kafka':
      return kafka
    case 'clickhouse':
      return clickhouse
    case 'sqlserver':
      return sqlserver
    case 'dameng':
      return dameng
    case 'postgresql':
      return postgresql
    case 'starrocks':
      return starrocks
    case 'doris':
      return doris
    default:
      return ''
  }
}

// const datasourceListFilter = computed(() => {
//   // 数据库列表filter 搜索功能
//   let temp = datasourceList.value.slice()
//   const selectDatasourceTypeTemp = selectDatasourceType.value.map((it) => it.toLowerCase())
//   if (selectDatasourceTypeTemp.length > 0) {
//     temp = datasourceList.value.filter((it) => {
//       return selectDatasourceTypeTemp.includes(it.type.toLowerCase())
//     })
//   }
//   if (searchDatasource.value) {
//     temp = datasourceList.value.filter((it) =>
//       it.datasourceName.toLowerCase().includes(searchDatasource.value.toLowerCase())
//     )
//   }
//   return temp
// })
const editableTabsValue = ref('') // 当前tab
const searchDatasource = ref('') // 数据库搜索值
const selectDatasourceType = ref('') // 数据库类型搜索
const selectType = ref('')
const selectName = ref('')
const editableTabs = ref([]) // tab list
const dbTypeList = ref([]) // 数据库类型list
const data = ref() // DatabaseInfo的参数, 用于组件中的一些请求
const esList = computed(() => {
  // DatabaseInfo的参数, 数据库列表中所有ES类型的数据库
  return datasourceList.value.filter((item) => item.type.toLowerCase() === 'elasticsearch')
})
const ckList = computed(() => {
  return datasourceList.value.filter((item) => item.type.toLowerCase() === 'clickhouse')
})
const pgList = computed(() => {
  return datasourceList.value.filter((item) => item.type.toLowerCase() === 'postgresql')
})
const mysqlList = computed(() => {
  return datasourceList.value.filter((item) => item.type.toLowerCase() === 'mysql')
})
const dorisList = computed(() => {
  return datasourceList.value.filter((item) => item.type.toLowerCase() === 'doris')
})
const showMenu = ref(false) // 右键菜单显示
const top = ref(0) // 右键菜单top
const left = ref(0) // 右键菜单left
const currentDatasource = ref({}) // 当前右键对象
const modifyDatasource = ref({}) // modify组件的Datasource属性值

const businessCardList = ref([])

const databaseTypeCard = ref([])

const isShowCreateTableDialog = ref(false)

const barData = ref({
  xAxisData: [],
  seriesData: []
})
const pieData = ref([])

const businessTrendData = ref({
  xAxisData: [],
  seriesData: [
    {
      name: '健康档案',
      type: 'line',
      smooth: true,
      symbol: 'circle',
      symbolSize: 8,
      data: []
    }
  ]
})

const getOverviewData = () => {
  // 获取业务类型连接数卡片数据
  findCountByBusiness().then((res) => {
    businessCardList.value = res.data
    console.log('businessCardList.value')
    console.log(businessCardList.value)
  })

  // 获取业务类型连接数增长趋势数据
  findTrendByBusiness().then((res) => {
    console.log(res)

    businessTrendData.value.xAxisData = res.data.timeData
    //将数据转换为echarts需要的格式，如果没有数据，就补0
    let seriesData = []
    res.data.data.forEach((item) => {
      console.log('item')
      console.log(item)
      //取出item对象的key当做name
      let temp = {
        name: Object.keys(item)[0],
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 8,
        data: []
      }

      //遍历item对象
      for (let key in item) {
        //遍历item[key]数组
        res.data.timeData.forEach((time) => {
          let find = item[key].find((it) => it.date == time)
          if (find) {
            temp.data.push(find.value)
          } else {
            temp.data.push(0)
          }
        })
      }
      //
      console.log('temp')
      console.log(temp)
      seriesData.push(temp)
    })
    businessTrendData.value.seriesData = seriesData
  })
  findCountByType().then((res) => {
    databaseTypeCard.value = res.data
    barData.value.xAxisData = res.data.map((item) => item.type)
    barData.value.seriesData = res.data.map((item) => item.value)
    pieData.value = res.data.map((item) => {
      return {
        value: item.value,
        name: item.type
      }
    })
  })
}
// getOverviewData()

const modifyKey = ref()

//数据源点击事件
const handleClickDatasource = function () {
  let findTab = editableTabs.value.find((item) => item.editData?._id == currentDatasource.value._id)
  if (findTab) {
    // ElMessage.warning('数据源已存在')
    editableTabsValue.value = findTab.name
    modifyDatasource.value[findTab.name] = findTab.editData
    editableTabsValue.value = findTab.name
    modifyKey.value = findTab.name
    return
  }
  const newTabName = `修改数据源[${currentDatasource.value.datasourceName}]`
  modifyKey.value = new Date().getTime()
  editableTabs.value.push({
    title: newTabName,
    name: modifyKey.value,
    content: 'New Tab content',
    editData: currentDatasource.value,
    type: 'edit'
  })
  modifyDatasource.value[modifyKey.value] = _cloneDeep(currentDatasource.value)
  editableTabsValue.value = modifyKey.value
}
const handleClickUser = function () {
  const newTabName = `用户管理[${currentDatasource.value.datasourceName}]`
  modifyKey.value = new Date().getTime()
  editableTabs.value.push({
    title: newTabName,
    name: modifyKey.value,
    content: 'New Tab content'
  })
  modifyDatasource.value[modifyKey.value] = _cloneDeep(currentDatasource.value)
  editableTabsValue.value = modifyKey.value
}
const handleClickStarrockts = () => {
  isShowStarrocktsDialog.value = true
}
const handleClickDoris = () => {
  isShowDorisDialog.value = true
}
const handleClickCreateTable = () => {
  isShowCreateTableDialog.value = true
}
// 关闭右键菜单
const handleCloseMenu = function () {
  if (DatabaseInfoRef?.value) {
    DatabaseInfoRef.value.forEach((item) => {
      item.closeMenu()
    })
  }
  showMenu.value = false
}

const handleNodeClick = (datasource) => {
  console.log(datasource)
  if (datasource._id) {
    let same = editableTabs.value.find((item) => {
      if (item.data) {
        return item.data._id == datasource._id
      } else {
        return false
      }
    })
    if (same) {
      data.value = same.data
      editableTabsValue.value = same.name
      return
    }
    data.value = datasource
    const now = new Date().getTime()
    editableTabs.value.push({
      title: datasource.datasourceName,
      name: now,
      content: 'New Tab content',
      data: datasource
    })
    editableTabsValue.value = now
  }
}
const nodeContextmenu = (e, data) => {
  console.log(e, data)
  if (data._id) {
    if (document.body.offsetHeight - e.pageY < 120) {
      top.value = e.pageY - 80
    } else {
      top.value = e.pageY //这个应该是相对于整个浏览器页面的y坐标，左上角为坐标原点（0,0）
    }
    left.value = e.pageX
    showMenu.value = true //显示菜单
    currentDatasource.value = _cloneDeep(data)
  }
}
const addTab = (targetName) => {
  const newTabName = `新增数据源`
  if (editableTabs.value.filter((it) => it.title === newTabName).length > 0) {
    ElMessage.warning('请先保存或关闭新增数据源')
    return
  }
  const now = new Date().getTime()
  editableTabs.value.push({
    title: newTabName,
    name: now,
    content: 'New Tab content'
  })
  editableTabsValue.value = now
}
const removeTab = (targetName) => {
  const tabs = editableTabs.value
  let activeName = editableTabsValue.value
  if (activeName === targetName) {
    tabs.forEach((tab, index) => {
      if (tab.name === targetName) {
        const nextTab = tabs[index + 1] || tabs[index - 1]
        if (nextTab) {
          activeName = nextTab.name
        }
      }
    })
  }

  editableTabsValue.value = activeName
  editableTabs.value = tabs.filter((tab) => tab.name !== targetName)
}
const listLoading = ref(false)
const handleRefresh = () => {
  listLoading.value = true
  createDBTypeList().then((res) => {
    dbTypeList.value = res.data
  })
  treeLoading.value = true
  getDatabaseList()
    .then((res) => {
      datasourceTree.value = res.data
    })
    .finally(() => {
      treeLoading.value = false
    })
  getDatabaseList()
    .then((res) => {
      datasourceList.value = res.data
    })
    .finally(() => {
      listLoading.value = false
    })
}
const timeID = ref(null)
const selectChange = () => {
  //1先清除之前的定时器
  clearTimeout(timeID.value)
  //2.开启本次定时器
  let name = ''
  if (selectType.value) {
    name = dataBaseType.value.find((item) => item.dictValue == selectType.value).dictLabel
  }
  let params = {}
  if (selectDatasourceType.value) params.dataBaseType = selectDatasourceType.value
  if (selectName.value) params.name = selectName.value
  if (selectType.value) params.businessType = selectType.value
  if (name) params.businessName = name
  timeID.value = setTimeout(() => {
    treeLoading.value = true
    getDatabaseList(params)
      .then((res) => {
        datasourceTree.value = res.data
      })
      .finally(() => {
        treeLoading.value = false
      })
  }, 500)
}
const tableName = ref('')
const getTableName = function (name) {
  tableName.value = name
}
const tabClick = (e) => {
  console.log(e)
  console.log(editableTabs.value)
  let tab = editableTabs.value.find((tab) => tab.name == e.paneName)
  console.log(tab)
  if (tab.data) {
    data.value = tab.data
  }
  if (tab.type == 'edit') {
    modifyDatasource.value[tab.name] = tab.editData
    editableTabsValue.value = tab.name
    modifyKey.value = tab.name
  }
}
handleRefresh()
</script>

<style lang="scss" scoped>
@import './style/index.scss';

.businessType {
  display: flex;
  justify-content: space-between;
  // margin-bottom: 8px;
  .type {
    width: 100%;
    :deep(.el-input) {
      .el-input__wrapper {
        font-size: 12px;
      }
    }
  }
}
:deep(.databaseNameInput) {
  .el-input__wrapper {
    font-size: 12px;
  }
}

.dataSourceList {
  box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.12);
  background: rgba(255, 255, 255, 1) !important;
  border-radius: 10px;
  .el-tree {
    background: none;
  }
}

.container-box-main {
  border-radius: 6px;
  box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.12);
  background: rgba(255, 255, 255, 1) !important;
  &.act {
    // background: none !important;
  }
}

.contextmenu {
  margin: 0;
  background: #2a2a42;
  z-index: 3000;
  position: fixed; //关键样式设置固定定位
  list-style-type: none;
  padding: 10px 0;
  border-radius: 4px;
  font-size: 14px;
  font-weight: 600;
  color: #b4b4b4;
  box-shadow: 2px 2px 3px 0 rgba(0, 0, 0, 0.3);
}

.contextmenu li {
  margin: 0;
  padding: 5px 16px;
  cursor: pointer;
  line-height: 26px;
}
.contextmenu li:hover {
  background: #4f4f7a;
}
.custom-tree-node {
  img {
    width: 20px;
    height: 20px;
    flex-shrink: 0;
  }
}
:deep(.el-tree-node) {
  .is-current {
    background-color: #ffa502 !important;
    --el-tree-node-hover-bg-color: #ffa502 !important;
    //鼠标移入的颜色为red
    // color: #fff;
  }
}
</style>
